<template>
    <el-tab-pane label="发布美食" name="recipe">
        <el-form :model="form" :rules="rules" ref="recipeForm" label-width="100px">
            <el-form-item label="分类" prop="category_id">
                <el-select v-model="form.category_id" placeholder="请选择种类" style="width:50%;">
                    <el-option v-for="category in categories" :key="category.id" :label="category.name"
                        :value="category.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="标题" prop="title">
                <el-input v-model="form.title" style="width: 100%;"></el-input>
            </el-form-item>
            <el-form-item label="封面图片">
                <el-upload action="#" list-type="picture-card" :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove" :http-request="uploadFile" :auto-upload="false" ref="upload">
                    <el-icon class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="标签" prop="tags">
                <div class="flex gap-2">
                    <el-tag v-for="tag in form.tags" :key="tag" closable :disable-transitions="false"
                        @close="handleClose(tag)">
                        {{ tag }}
                    </el-tag>
                    <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="w-20" size="small"
                        @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
                    <el-button v-else class="button-new-tag" size="small" @click="showInput">
                        添加标签
                    </el-button>
                </div>
            </el-form-item>
            <el-form-item label="产地" prop="origin">
                <el-input v-model="form.origin" style="width: 100%;"></el-input>
            </el-form-item>
            <el-form-item label="推荐理由" prop="reason">
                <el-input type="textarea" v-model="form.reason" style="width: 100%;" :rows="2"></el-input>
            </el-form-item>
            <el-form-item label="内容" prop="content">
                <el-input type="textarea" v-model="form.content" style="width: 100%;" :rows="5"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('recipeForm')">提交</el-button>
                <el-button @click="resetForm('recipeForm')">重置</el-button>
            </el-form-item>
        </el-form>
        <el-dialog :visible.sync="dialogVisible" :modal-append-to-body="false">
            <img width="100%" :src="dialogImageUrl" alt="预览图片">
        </el-dialog>
    </el-tab-pane>
</template>

<script setup>
import { ref, nextTick, reactive } from 'vue';
import { getcategory, postfood } from '~/api/release';
import { ElNotification } from 'element-plus';
import { useCookies } from '@vueuse/integrations/useCookies';

const categories = ref([]);
const cookies = useCookies()
const state = reactive({ category: '美食' });
getcategory(state).then(res => {
    console.log(res)
    categories.value = res.categories
})

const form = ref({
    user_id: cookies.get('use_id'),
    category_id: '',
    title: '',
    tags: [],
    origin: '',
    reason: '',
    content: '',
    coverImage:''
});
const rules = reactive({
    category_id: [
        { required: true, message: '请选择种类', trigger: 'change' }
    ],
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    tags: [
        { type: 'array', required: true, message: '请添加至少一个标签', trigger: 'change' }
    ],
    origin: [
        { required: true, message: '请输入产地', trigger: 'blur' },
        { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
    ],
    reason: [
        { required: true, message: '请输入推荐理由', trigger: 'blur' },
        { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
    ],
    content: [
        { required: true, message: '请输入内容', trigger: 'blur' },
        { min: 2, max: 1000, message: '长度在 2 到 1000 个字符', trigger: 'blur' }
    ]
});
const upload = ref(null);
const recipeForm = ref(null);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const inputValue = ref('');
const inputVisible = ref(false);
const InputRef = ref(null);

const submitForm = (formName) => {
    recipeForm.value.validate((valid) => {
        if (valid) {
            // 手动触发文件上传
            upload.value.submit();
            console.log(form.value.coverImage)
            // 延迟以确保文件上传完成
            setTimeout(() => {
                if (form.value.coverImage) {
                    const formData = new FormData();
                    formData.append('user_id', form.value.user_id);
                    formData.append('category_id', form.value.category_id);
                    formData.append('title', form.value.title);
                    formData.append('tags', JSON.stringify(form.value.tags));
                    formData.append('origin', form.value.origin);
                    formData.append('reason', form.value.reason);
                    formData.append('content', form.value.content);
                    formData.append('image', form.value.coverImage);
                    postfood(formData).then(response => {
                        ElNotification({
                            message: "美食发布成功",
                            type: 'success',
                            duration: 3000
                        })
                        resetForm(formName);
                        location.reload();
                    }).catch(error => {
                        ElNotification({
                            message: "美食发布失败",
                            type: 'error',
                            duration: 3000
                        })
                    });
                } else {
                    ElNotification({
                        message: "图片未上传",
                        type: 'error',
                        duration: 3000
                    })
                }
            }, 2000); // 延迟1秒以确保文件上传完成
        } else {
            ElNotification({
                message: "验证失败",
                type: 'error',
                duration: 3000
            })
            console.log('验证失败');
            return false;
        }
    });
};

const resetForm = (formName) => {
    recipeForm.value.resetFields();
};


const handleRemove = (file, fileList) => {
    console.log(file, fileList);
   
};

const handlePictureCardPreview = (file) => {
    console.log(file);
    window.open(file.url, '_blank');  
};


const uploadFile = (options) => {
    console.log(options);
    form.value.coverImage = options.file;   
};

const handleClose = (tag) => {
    form.value.tags.splice(form.value.tags.indexOf(tag), 1);
};

const showInput = () => {
    inputVisible.value = true;
    nextTick(() => {
        InputRef.value.input.focus();
    });
};

const handleInputConfirm = () => {
    if (inputValue.value) {
        form.value.tags.push(inputValue.value);
    }
    inputVisible.value = false;
    inputValue.value = '';
};

</script>

<style scoped>
/* 表单整体布局 */
.el-form {
    max-width: 1100px;
    margin: 0 auto;
    padding: 20px;
    background-color: #ffffff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 可选：进一步美化表单项 */
.el-form-item {
    margin-bottom: 20px;
}

.el-input__inner,
.el-textarea__inner {
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.el-input__inner:focus,
.el-textarea__inner:focus {
    border-color: #409eff;
    outline: 0;
}

.el-select .el-input__inner {
    height: 40px;
}

.el-upload--picture-card {
    width: 100px;
    height: 100px;
    line-height: 100px;
}

.el-button {
    width: 100px;
    height: 40px;
    border-radius: 4px;
    transition: background-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.el-button--primary {
    background-color: #409eff;
    border-color: #409eff;
}

.el-button--primary:hover {
    background-color: #66b1ff;
    border-color: #66b1ff;
}

.el-button:hover {
    background-color: #f2f6fc;
    border-color: #dcdfe6;
}

.el-form-item__label {
    font-weight: bold;
    color: #303133;
}

.flex {
    display: flex;
    align-items: center;
}

.gap-2 {
    gap: 8px;
}

.w-20 {
    width: 80px;
}
</style>